package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.BeanUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.api.model.LoginUser;
import org.dromara.system.domain.EmailAccount;
import org.dromara.system.domain.EmailQueue;
import org.dromara.system.domain.vo.PayOrderTrackVo;
import org.dromara.system.elastic.entity.PayOrderEs;
import org.dromara.system.kernel.OrderSearchKernel;
import org.dromara.system.kernel.SendEmailKernel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.EmailListBo;
import org.dromara.system.domain.vo.EmailListVo;
import org.dromara.system.domain.EmailList;
import org.dromara.system.mapper.EmailListMapper;
import org.dromara.system.service.IEmailListService;

import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 邮件记录Service业务层处理
 *
 * @author Gavino
 * @date 2024-11-18
 */
@RequiredArgsConstructor
@Service
public class EmailListServiceImpl implements IEmailListService {

    private final EmailListMapper baseMapper;

    /**
     * 更新邮件状态
     *
     * @param queueId   队列ID
     * @param status    当前状态
     * @param newStatus 更新后状态
     */
    @Override
    public void updateEmailStatusByQueueId(Long queueId, Integer status, Integer newStatus) {
        LambdaUpdateWrapper<EmailList> update = new LambdaUpdateWrapper<>();
        update.eq(EmailList::getQueueId, queueId);
        update.eq(EmailList::getStatus, status);

        update.set(EmailList::getStatus, newStatus);
        baseMapper.update(null, update);
    }

    /**
     * 查询邮件记录
     *
     * @param emailId 主键
     * @return 邮件记录
     */
    @Override
    public EmailListVo queryById(Long emailId){
        return baseMapper.selectVoById(emailId);
    }

    /**
     * 查询邮件记录
     *
     * @param emailId 主键
     * @return 邮件记录
     */
    @Override
    public EmailList selectById(Long emailId){
        return baseMapper.selectById(emailId);
    }

    /**
     * 分页查询邮件记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 邮件记录分页列表
     */
    @Override
    public TableDataInfo<EmailListVo> queryPageList(EmailListBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EmailList> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(EmailList::getStatus);
        lqw.orderByDesc(EmailList::getCreateTime);
        Page<EmailListVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的邮件记录列表
     *
     * @param bo 查询条件
     * @return 邮件记录列表
     */
    @Override
    public List<EmailListVo> queryList(EmailListBo bo) {
        LambdaQueryWrapper<EmailList> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(EmailList::getSendTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询符合条件的邮件记录列表
     *
     * @param bo 查询条件
     * @return 邮件记录列表
     */
    @Override
    public List<EmailList> selectList(EmailListBo bo) {
        LambdaQueryWrapper<EmailList> lqw = buildQueryWrapper(bo);
        return baseMapper.selectList(lqw);
    }

    private LambdaQueryWrapper<EmailList> buildQueryWrapper(EmailListBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<EmailList> lqw = Wrappers.lambdaQuery();

        if(!LoginHelper.isSuperAdmin()) {
            // 非超级管理员查询自己创建的或自己代理的
            Long userId = LoginHelper.getUserId();
            if(LoginHelper.isAgent()) {
                lqw.and(qw -> qw.eq(EmailList::getCreateId, userId).or().eq(EmailList::getAgentId, userId));
            } else {
                lqw.eq(EmailList::getCreateId, userId);
            }
            // 未删除的
            bo.setIsDelete(0);
        }

        if (bo.getEmailIds() != null && !bo.getEmailIds().isEmpty()) {
           lqw.in(EmailList::getEmailId, bo.getEmailIds());
        }
        lqw.eq(bo.getType() != null, EmailList::getType, bo.getType());
        lqw.eq(bo.getQueueId() != null, EmailList::getQueueId, bo.getQueueId());
        lqw.eq(bo.getTemplateId() != null, EmailList::getTemplateId, bo.getTemplateId());
        lqw.eq(bo.getOrderId() != null, EmailList::getOrderId, bo.getOrderId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), EmailList::getOrderNo, bo.getOrderNo());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiveEmail()), EmailList::getReceiveEmail, bo.getReceiveEmail());
        lqw.eq(StringUtils.isNotBlank(bo.getDyncParam()), EmailList::getDyncParam, bo.getDyncParam());
        lqw.eq(bo.getSendEmailId() != null, EmailList::getSendEmailId, bo.getSendEmailId());
        lqw.eq(StringUtils.isNotBlank(bo.getSendEmailAct()), EmailList::getSendEmailAct, bo.getSendEmailAct());
        lqw.eq(bo.getSendTime() != null, EmailList::getSendTime, bo.getSendTime());
        lqw.eq(bo.getStatus() != null, EmailList::getStatus, bo.getStatus());
        lqw.eq(bo.getIsDelete() != null, EmailList::getIsDelete, bo.getIsDelete());
        lqw.eq(bo.getErrTime() != null, EmailList::getErrTime, bo.getErrTime());
        lqw.eq(StringUtils.isNotBlank(bo.getErrContent()), EmailList::getErrContent, bo.getErrContent());
        lqw.eq(bo.getCreateId() != null, EmailList::getCreateId, bo.getCreateId());
        lqw.like(StringUtils.isNotBlank(bo.getCreateName()), EmailList::getCreateName, bo.getCreateName());
        lqw.eq(bo.getUpdateId() != null, EmailList::getUpdateId, bo.getUpdateId());
        lqw.like(StringUtils.isNotBlank(bo.getUpdateName()), EmailList::getUpdateName, bo.getUpdateName());
        return lqw;
    }

    /**
     * 新增邮件记录
     *
     * @param bo 邮件记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(EmailListBo bo) {
        EmailList add = MapstructUtils.convert(bo, EmailList.class);
        validEntityBeforeSave(add);
        add.setIsDelete(0);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setEmailId(add.getEmailId());
        }
        return flag;
    }

    /**
     * 修改邮件记录
     *
     * @param bo 邮件记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(EmailListBo bo) {
        EmailList update = MapstructUtils.convert(bo, EmailList.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EmailList entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除邮件记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        LambdaQueryWrapper<EmailList> query = new LambdaQueryWrapper<>();
        query.in(EmailList::getEmailId, ids);
        if (LoginHelper.isAgent()) {
            query.eq(EmailList::getCreateId, LoginHelper.getUserId());
        }
        return baseMapper.delete(query) > 0;
    }
}
